/**
 * Collection Task React Query Hooks
 * 采集任务管理钩子 (FR-006 ~ FR-009a)
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { message } from 'antd'
import { queryKeys } from '@/config/queryClient'
import * as collectionApi from '@/services/api/collection'
import type { CollectionTask, CollectionTaskCreateRequest, PageResponse } from '@/services/models/types'
import { TaskStatus } from '@/services/models/types'

// ============================================
// Query Hooks - 查询钩子
// ============================================

/**
 * 采集任务列表查询 (FR-006)
 */
export const useCollectionTaskList = (params: any, options?: any) => {
  return useQuery<PageResponse<CollectionTask>>({
    queryKey: queryKeys.collectionTasks.list(params),
    queryFn: async () => {
      const response = await collectionApi.listCollectionTasks(params)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    staleTime: 30000, // 30s - shorter than datasource since tasks change frequently
    ...options,
  })
}

/**
 * 采集任务详情查询 (FR-007)
 */
export const useCollectionTask = (id: number, options?: any) => {
  return useQuery({
    queryKey: queryKeys.collectionTasks.detail(id),
    queryFn: async () => {
      const response = await collectionApi.getCollectionTask(id)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    enabled: !!id,
    staleTime: 10000, // 10s - task status may change quickly
    ...options,
  })
}

// ============================================
// Mutation Hooks - 变更钩子
// ============================================

/**
 * 创建采集任务 (FR-008)
 */
export const useCreateCollectionTask = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (data: CollectionTaskCreateRequest) => {
      const response = await collectionApi.createCollectionTask(data)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.lists() })
      message.success(`采集任务 "${data.id}" 已创建,任务正在执行中...`)
    },
    onError: (error: Error) => {
      message.error(`创建采集任务失败: ${error.message}`)
    },
  })
}


/**
 * 启动采集任务
 */
export const useStartCollectionTask = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await collectionApi.startCollectionTask(id)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    onSuccess: (data, id) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.detail(id) })
      message.success(`采集任务已启动,任务ID: ${data.id}`)
    },
    onError: (error: Error) => {
      message.error(`启动失败: ${error.message}`)
    },
  })
}

/**
 * 取消采集任务 (FR-009)
 */
export const useCancelCollectionTask = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await collectionApi.cancelCollectionTask(id)
      if (!response.success) throw new Error(response.message)
      return id
    },
    onMutate: async (id) => {
      // Optimistic update - immediately show cancelling state
      await queryClient.cancelQueries({ queryKey: queryKeys.collectionTasks.detail(id) })
      const previousData = queryClient.getQueryData<CollectionTask>(
        queryKeys.collectionTasks.detail(id)
      )

      if (previousData) {
        queryClient.setQueryData<CollectionTask>(
          queryKeys.collectionTasks.detail(id),
          {
            ...previousData,
            status: 'CANCELLED' as any, // Optimistic status
          }
        )
      }

      return { previousData }
    },
    onSuccess: (id) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.detail(id) })
      message.success('采集任务已取消')
    },
    onError: (error: Error, id, context) => {
      // Rollback optimistic update
      if (context?.previousData) {
        queryClient.setQueryData(
          queryKeys.collectionTasks.detail(id),
          context.previousData
        )
      }
      message.error(`取消失败: ${error.message}`)
    },
  })
}

/**
 * 重试失败的表采集 (FR-009a)
 */
export const useRetryFailedTables = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      const response = await collectionApi.retryFailedTables(id)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    onSuccess: (data, id) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.lists() })
      queryClient.invalidateQueries({ queryKey: queryKeys.collectionTasks.detail(id) })
      message.success(`正在重试失败的表,任务ID: ${data.id}`)
    },
    onError: (error: Error) => {
      message.error(`重试失败: ${error.message}`)
    },
  })
}

/**
 * 轮询采集任务状态 (用于任务监控页面)
 * 当任务状态为RUNNING时,每5秒自动刷新
 */
export const useCollectionTaskPolling = (id: number, enabled: boolean = true) => {
  return useQuery({
    queryKey: [...queryKeys.collectionTasks.detail(id), 'polling'],
    queryFn: async () => {
      const response = await collectionApi.getCollectionTask(id)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    enabled: enabled && !!id,
    refetchInterval: (query) => {
      // Only poll if task is still running
      if (query.state.data && (query.state.data.status === TaskStatus.RUNNING || query.state.data.status === TaskStatus.PENDING)) {
        return 5000 // 5 seconds
      }
      return false // Stop polling
    },
    staleTime: 0, // Always fetch fresh data when polling
  })
}
